<template>
  <div class="charity-center">
    <div class="operation-bar">
      <div class="left-operations">
        <el-button type="primary" @click="handleAdd">+ 添加</el-button>
        <el-button type="danger" @click="handleBatchDelete" :disabled="!selectedRows.length">
          批量删除
        </el-button>
      </div>
      
      <div class="search-area">
        <el-select v-model="searchType" placeholder="选择咨询师" clearable>
          <el-option
            v-for="item in consultantList"
            :key="item.consultantId"
            :label="item.fullName"
            :value="item.consultantId"
          />
        </el-select>
        <el-input
          v-model="searchKeyword"
          placeholder="搜索标题"
          class="search-input"
        />
        <el-button type="primary" @click="handleSearch">
          <el-icon><Search /></el-icon> 搜索
        </el-button>
        <el-button @click="handleReset">重置</el-button>
      </div>
    </div>

    <el-table
      :data="charityList"
      style="width: 100%"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column label="封面" width="120">
        <template #default="scope">
          <el-image
            :src="scope.row.imageUrl"
            :preview-src-list="[scope.row.imageUrl]"
            fit="cover"
            style="width: 80px; height: 80px"
          />
        </template>
      </el-table-column>
      <el-table-column prop="title" label="标题" />
      <el-table-column prop="content" label="摘要" show-overflow-tooltip />
      <el-table-column prop="publishTime" label="上传时间" width="180">
        <template #default="scope">
          {{ formatDate(scope.row.publishTime) }}
        </template>
      </el-table-column>
      <el-table-column label="用户操作" width="180">
        <template #default="scope">
          <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button
            size="small"
            type="danger"
            @click="handleDelete(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination">
      <div class="pagination-left">
        <span class="total-text">Total {{ total }}</span>
        <el-select v-model="pageSize" style="width: 120px" @change="handleSizeChange">
          <el-option label="5/page" :value="5" />
          <el-option label="10/page" :value="10" />
          <el-option label="20/page" :value="20" />
        </el-select>
        <el-pagination
          v-model:current-page="currentPage"
          :page-size="pageSize"
          :total="total"
          layout="prev, pager, next"
          @current-change="handleCurrentChange"
        />
      </div>
      <div class="goto-page">
        Go to <el-input v-model="gotoPage" style="width: 60px" @keyup.enter="handleGotoPage" />
      </div>
    </div>

    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '添加公益活动' : '编辑公益活动'"
      width="50%"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="咨询师" prop="consultantId">
          <el-select v-model="form.consultantId" placeholder="请选择咨询师">
            <el-option
              v-for="item in consultantList"
              :key="item.consultantId"
              :label="item.fullName"
              :value="item.consultantId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="标题" prop="title">
          <el-input v-model="form.title" />
        </el-form-item>
        <el-form-item label="摘要" prop="content">
          <el-input v-model="form.content" type="textarea" :rows="3" />
        </el-form-item>
        <el-form-item label="封面图片" prop="imageUrl">
          <el-upload
            class="avatar-uploader"
            action="admin/upload"
            :show-file-list="false"
            :on-success="handleUploadSuccess"
          >
            <img v-if="form.imageUrl" :src="form.imageUrl" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { Search, Plus } from '@element-plus/icons-vue'
import axios from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus'

export default {
  name: 'Gongyizhongxin',
  components: {
    Search,
    Plus
  },
  data() {
    return {
      charityList: [],
      currentPage: 1,
      pageSize: 5,
      total: 0,
      loading: false,
      searchType: '',
      searchKeyword: '',
      gotoPage: '',
      selectedRows: [],
      consultantList: [],
      dialogVisible: false,
      dialogType: 'add', // 'add' 或 'edit'
      form: {
        id: null,
        title: '',
        content: '',
        imageUrl: '',
        consultantId: '',
        publishTime: null
      },
      rules: {
        consultantId: [{ required: true, message: '请选择咨询师', trigger: 'change' }],
        title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
        content: [{ required: true, message: '请输入摘要', trigger: 'blur' }],
        imageUrl: [{ required: true, message: '请上传封面图片', trigger: 'change' }]
      }
    }
  },
  created() {
    this.fetchCharityList()
    this.fetchConsultantList()
  },
  methods: {
    async fetchCharityList() {
      this.loading = true
      try {
        let response;
        // 如果有咨询师ID，优先按咨询师搜索
        if (this.searchType) {
          response = await axios.get(`charityActivity/searchByConsultants/${this.searchType}`)
        }
        // 如果有标题关键字，按标题搜索
        else if (this.searchKeyword) {
          response = await axios.get('charityActivity/search', {
            params: { title: this.searchKeyword }
          })
        }
        // 如果都没有，获取所有数据
        else {
          response = await axios.get('charityActivity/listAll', {
            params: {
              page: this.currentPage,
              pageSize: this.pageSize
            }
          })
        }

        if (response.data.code === 200) {
          // 处理不同接口返回的数据结构
          if (Array.isArray(response.data.data)) {
            // 搜索接口返回的是数组
            this.charityList = response.data.data
            this.total = response.data.data.length
          } else {
            // listAll 接口返回的是分页对象
            this.charityList = response.data.data.list || []
            this.total = response.data.data.total || 0
          }
        } else {
          ElMessage.error(response.data.msg || '获取数据失败')
        }
      } catch (error) {
        console.error('获取公益活动列表失败:', error)
        ElMessage.error('获取公益活动列表失败')
      } finally {
        this.loading = false
      }
    },
    handleCurrentChange(page) {
      this.currentPage = page
      this.fetchCharityList()
    },
    handleSizeChange(size) {
      this.pageSize = size
      this.currentPage = 1
      this.fetchCharityList()
    },
    handleGotoPage() {
      const page = parseInt(this.gotoPage)
      if (page && page > 0 && page <= Math.ceil(this.total / this.pageSize)) {
        this.currentPage = page
        this.fetchCharityList()
      }
      this.gotoPage = ''
    },
    handleSearch() {
      this.currentPage = 1
      // 不能同时使用两个搜索条件
      if (this.searchType && this.searchKeyword) {
        ElMessage.warning('请只选择一种搜索方式：按咨询师或按标题')
        return
      }
      this.fetchCharityList()
    },
    handleReset() {
      this.searchType = ''
      this.searchKeyword = ''
      this.currentPage = 1
      this.fetchCharityList()
    },
    handleSelectionChange(rows) {
      this.selectedRows = rows
    },
    handleAdd() {
      this.dialogType = 'add'
      this.form = {
        id: null,
        title: '',
        content: '',
        imageUrl: '',
        consultantId: '',
        publishTime: null
      }
      this.dialogVisible = true
    },
    handleEdit(row) {
      this.dialogType = 'edit'
      this.form = { ...row }
      this.dialogVisible = true
    },
    handleDelete(row) {
      ElMessageBox.confirm('确定要删除该项吗？', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(async () => {
        try {
          const response = await axios.delete(`charityActivity/delete/${row.id}`)
          if (response.data.code === 200) {
            ElMessage.success('删除成功')
            this.fetchCharityList()
          } else {
            ElMessage.error(response.data.msg || '删除失败')
          }
        } catch (error) {
          console.error('删除失败:', error)
          ElMessage.error('删除失败')
        }
      }).catch(() => {
        ElMessage.info('已取消删除')
      })
    },
    async handleBatchDelete() {
      if (this.selectedRows.length === 0) {
        ElMessage.warning('请选择要删除的项目')
        return
      }
      
      ElMessageBox.confirm(
        `确定要删除选中的 ${this.selectedRows.length} 项吗？`,
        '警告',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).then(async () => {
        try {
          const ids = this.selectedRows.map(row => row.id)
          const response = await axios.delete(`charityActivity/batchDelete?ids=${ids.join(',')}`)
          
          if (response.data.code === 200) {
            ElMessage.success('批量删除成功')
            this.fetchCharityList()
          } else {
            ElMessage.error(response.data.msg || '批量删除失败')
          }
        } catch (error) {
          console.error('批量删除失败:', error)
          ElMessage.error('批量删除失败')
        }
      }).catch(() => {
        ElMessage.info('已取消删除')
      })
    },
    async handleSubmit() {
      if (!this.$refs.formRef) return
      await this.$refs.formRef.validate(async (valid) => {
        if (valid) {
          try {
            const url = this.dialogType === 'add' 
              ? 'charityActivity/add'
              : 'charityActivity/update'
            
            const response = await axios.post(url, this.form)
            if (response.data.code === 200) {
              ElMessage.success(this.dialogType === 'add' ? '添加成功' : '修改成功')
              this.dialogVisible = false
              this.fetchCharityList()
            } else {
              ElMessage.error(response.data.msg || (this.dialogType === 'add' ? '添加失败' : '修改失败'))
            }
          } catch (error) {
            console.error(this.dialogType === 'add' ? '添加失败:' : '修改失败:', error)
            ElMessage.error(this.dialogType === 'add' ? '添加失败' : '修改失败')
          }
        }
      })
    },
    handleUploadSuccess(response) {
      if (response.code === 200) {
        this.form.imageUrl = response.msg
        ElMessage.success('上传成功')
      } else {
        ElMessage.error('上传失败')
      }
    },
    formatDate(date) {
      if (!date) return '暂无'
      return new Date(date).toLocaleString()
    },
    async fetchConsultantList() {
      try {
        const response = await axios.get('charityActivity/list')
        if (response.data.code === 200) {
          this.consultantList = response.data.data.map(item => ({
            consultantId: item.consultantId,
            fullName: item.fullName,
            avatar: item.consultantAvatar
          }))
        } else {
          ElMessage.error(response.data.msg || '获取咨询师列表失败')
        }
      } catch (error) {
        console.error('获取咨询师列表失败:', error)
        ElMessage.error('获取咨询师列表失败')
      }
    }
  }
}
</script>

<style scoped>
.charity-center {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100%;
}

.operation-bar {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.left-operations {
  display: flex;
  gap: 10px;  /* 按钮之间的间距 */
}

.search-area {
  display: flex;
  gap: 10px;
  align-items: center;
}

.search-input {
  width: 200px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 15px;
}

.pagination-left {
  display: flex;
  align-items: center;
  gap: 15px;
}

.total-text {
  color: #606266;
}

.goto-page {
  display: flex;
  align-items: center;
  gap: 5px;
}

:deep(.el-table) {
  margin-top: 20px;
  background-color: white;
}

:deep(.el-table th) {
  background-color: #f2f2f2;
  border-bottom: 1px solid #ebeef5;
  border-top: 1px solid #ebeef5;
  color: #606266;
}

:deep(.el-table td) {
  border-bottom: 1px solid #ebeef5;
}

:deep(.el-table tr:hover) {
  background-color: #fafafa;
}

:deep(.el-table th.el-table__cell) {
  font-weight: 600;
  color: #606266;
}

.avatar-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 178px;
  height: 178px;
}

.avatar-uploader:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
  line-height: 178px;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
